function sortedCommByDigs(arr1, arr2) {
    let set1 = new Set(arr1), set2 = new Set(arr2), it = set1.entries(), res = [];
    var f = (x) => {
        var dr = [...'' + x].reduce((s, v) => s += +v, 0);
        var dsddr = [...'' + dr].reduce((s, v) => s += (+v) ** 2, 0);
        return dsddr + dr;
    }
    for (let x of it)
        if (set2.has(x[0])) res.push([x[0], f(x[0])]);

    return res.sort((a, b) => b[1] === a[1] ? a[0] - b[0] : b[1] - a[1]).map(e => e[0]);
}
